//
//  KDLiaisonProfessionController.m
//  PublicSentimentMonitorSystem
//
//  Created by 魏强 on 15/6/21.
//  Copyright (c) 2015年 魏强. All rights reserved.
//  我的设置－－我的上报页面

#import "KDLiaisonProfessionController.h"
#import "GBJobTableView.h"
#import <MediaPlayer/MediaPlayer.h>
#import "ImgShowViewController.h"
#import <MobileCoreServices/UTCoreTypes.h>
#import "JobSingleViewController.h"
#import "GBReportTableView.h"
#import "AFNetworking.h"
#import "AFHTTPRequestOperation.h"
#import "GBReportViewController.h"
//#import "GBButtonCorners.h"
#import "GBShortMessageTableView.h"
#import "GBShortMessageViewController.h"

#define baseUrl @"&method=getMobileReportList&token="
#define p @"&p=1&limit=10&count=0"

@interface KDLiaisonProfessionController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextViewDelegate,UITextFieldDelegate>
{
    //6.19改
    NSString *reportUrl; //上报列表的url
    NSString *hotpointUrl; //热点的url
    NSMutableArray *urlArray; //盛放url的数组
    
    UIBarButtonItem *rightPhotoBtn; //右上角照片button，从照片库或摄像头上传照片或视频
    UIButton *addPhotoBtn; //增加照片的按钮
    LXActionSheet *actionSheet; //点击右上角照片按钮，出现的选择菜单
    float PhotoWidth; //每张照片的宽度；
    int photoCount; //用于保存照片的个数
    int photoColumn; //当每一行的照片满了，下一回照片个数清零
    UIButton *cancleBtn; //取消选择照片按钮
    UIButton *sendBtn; //发送消息按钮；
    
    UITextView *GBtextView; //用户输入文字的textview,放在photoview上；
    UILabel *GBLable; //textview默认的内容放在photoview上；
    
    LXActionSheet *actionSheetVideo; //点击选择是否写入照片库 0-写入 1-取消
    UIButton *cameraBtn; //右上角的上报按钮，既相机样式的按钮
    
    UIImagePickerController *ipc; //显示照片的界面
    NSMutableArray *imgListP; //用于盛放用户选择的照片
    NSMutableArray *imgCopy; //用于盛放新照片的数组
    
    //6.27
    GBReportTableView *reportTableView; //上报列表
    NSString *typeKind; //选择的上报类型
    
    //11.23
    //UIButton *shortmessageBtn; //短信按钮
    
    // 2016/3/23
    UILongPressGestureRecognizer *longPress; // 长按手势
}
@end

@implementation KDLiaisonProfessionController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"上报中心";
    
    typeKind = @"1";
    //初始化两个界面url
    [self createUrl];
    //初始化两个tableview
    [self createTableView];
    //跳转单个界面的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(goToTheSinglePh:) name:@"goToTheSingleViewRp" object:nil];
    
    imgListP = [NSMutableArray array];
    imgCopy = [NSMutableArray array];
    PhotoWidth = (self.view.frame.size.width - 50) / 4.0;
    photoCount = 0;
    photoColumn = 0;
    
    //初始化右上角照片btn;
    [self createPhotoButton];
    // Do any additional setup after loading the view.
}

#pragma mark - 跳转到单个界面
-(void)goToTheSinglePh:(NSNotification *)note
{
    NSDictionary *user = [note userInfo];
    JobSingleViewController *single = [[JobSingleViewController alloc] init];
    
    single.whichKind = [user objectForKey:@"singleWhichType"];
    single.uid = [user objectForKey:@"singleClueId"];
    single.titleString = [user objectForKey:@"singleTitle"];
    single.timeString = [user objectForKey:@"singleDate"];
    single.kindString = [user objectForKey:@"singleClueTypeId"];
    single.taskRequired = [user objectForKey:@"singleWorkAsk"];
    single.taskDescription = [user objectForKey:@"singleDescription"];
    single.taskNei = [user objectForKey:@"singleNeiRong"];
    single.location = [user objectForKey:@"singleRegion"];
    single.websiteType = [user objectForKey:@"singleWebsiteType"];
    single.author = [user objectForKey:@"singleAuthor"];
    single.webName = [user objectForKey:@"singleWebName"];
    single.messageTime = [user objectForKey:@"singleMessageTime"];
    single.messageContent = [user objectForKey:@"singleMessageContent"];
    single.reportType = [user objectForKey:@"reportType"];
    single.infoType = [user objectForKey:@"infoType"];
    single.recheckPeople = [user objectForKey:@"recheckPeople"];
    single.approvePeople = [user objectForKey:@"approvePeople"];
    single.geographyRegion = [user objectForKey:@"physicsRegion"];
    single.activityType = [user objectForKey:@"activityType"];
    single.infomationLevel = [user objectForKey:@"informationLevel"];
    single.infomationRegion = [user objectForKey:@"informationRegion"];
    single.mainKeyWord = [user objectForKey:@"mainKeyWord"];
    single.subKeyWord = [user objectForKey:@"subKeyWord"];
    single.messageTitle = [user objectForKey:@"singleMessageTitle"];
    //KDLog(@"%@",single.whichKind);
    
    NSArray *arra = [user objectForKey:@"singlePhotoUrlArray"];
    //KDLog(@"%@",arra);
    for(int i = 0; i < arra.count; i++)
    {
        [single.photoArrayUrl addObject:arra[i]];
    }
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:single.jobName style:UIBarButtonItemStylePlain target:nil action:nil];
    [self.navigationItem setBackBarButtonItem:backItem];
    //KDLog(@"%@",single.whichPage);
    single.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:single animated:YES];
    single.hidesBottomBarWhenPushed = NO;
}

#pragma mark - 初始化两个界面url
-(void)createUrl
{
    KDAccount *accout = [KDAccountTool account];
    urlArray = [NSMutableArray array];
    reportUrl = [NSString stringWithFormat:@"%@%@%@&p=1&limit=10&count=0", ServerActionAddr, baseUrl,accout.token];
    [urlArray addObject:reportUrl];
}

#pragma mark - 初始化两个tableview(上报和短信界面)
-(void)createTableView
{
    //创建上报界面
    reportTableView = [[GBReportTableView alloc] initWithFrame:CGRectMake(0, 4, screenW, screenH - 64)];
    reportTableView.Jurl = urlArray[0];
    KDLog(@"reportview = %@",reportTableView.Jurl);
    [self.view addSubview:reportTableView];
}

#pragma mark - 初始化右上角照片btn和左上角的返回按钮
-(void)createPhotoButton
{
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    leftView.backgroundColor = KDColor;
    
    UIButton *backButton = [UIButton buttonWithType:0];
    backButton.frame = CGRectMake(0, 0, 40, 40);
    [backButton addTarget:self action:@selector(GoToTheBack) forControlEvents:UIControlEventTouchUpInside];
    [backButton setImage:[UIImage imageNamed:@"leftArrow"] forState:UIControlStateNormal];
    
    [leftView addSubview:backButton];
    
    UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    rightView.backgroundColor = KDColor;
    
//    shortmessageBtn = [UIButton buttonWithType:0];
//    shortmessageBtn.frame = CGRectMake(50, 10, 20, 20);
//    [shortmessageBtn addTarget:self action:@selector(PickTHeShortmessage) forControlEvents:UIControlEventTouchUpInside];
//    [shortmessageBtn setImage:[UIImage imageNamed:@"report_message"] forState:UIControlStateNormal];
    
    cameraBtn = [UIButton buttonWithType:0];
    cameraBtn.frame = CGRectMake(0, 0, 40, 40);
    [cameraBtn addTarget:self action:@selector(PickThePhoto) forControlEvents:UIControlEventTouchUpInside];
    [cameraBtn setImage:[UIImage imageNamed:@"拍照上报"] forState:UIControlStateNormal];
    
    longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressToDo:)];
    longPress.minimumPressDuration = 1.0;
    [cameraBtn addGestureRecognizer:longPress];
    
//  [rightView addSubview:shortmessageBtn];
    [rightView addSubview:cameraBtn];
    
    UIBarButtonItem *menuButton1 = [[UIBarButtonItem alloc] initWithCustomView:leftView];
    self.navigationItem.leftBarButtonItem = menuButton1;
    UIBarButtonItem *menuButton2 = [[UIBarButtonItem alloc] initWithCustomView:rightView];
    self.navigationItem.rightBarButtonItem = menuButton2;
}

#pragma mark - 响应长按手势的代码
-(void)longPressToDo:(UILongPressGestureRecognizer *)gesture
{
    if(gesture.state == UIGestureRecognizerStateBegan)
    {
        //选择图片成功后跳转界面
        GBReportViewController *collect = [[GBReportViewController alloc] init];
        collect.longPress = 2;
        UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
        self.navigationController.navigationBar.hidden = NO;
        [self.navigationItem setBackBarButtonItem:backItem];
        [self.navigationController pushViewController:collect animated:YES];
    }
}

#pragma mark - 返回主界面
-(void)GoToTheBack
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 点击右上角按钮的操作
-(void)PickThePhoto
{
    photoCount = 0;
    photoColumn = 0;
    [imgCopy removeAllObjects];
    [imgListP removeAllObjects];
    
    if (cameraBtn.isEnabled)
    {
        actionSheet = [[LXActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@[@"拍照",@"从手机相册选择"]];
        
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        [actionSheet showInView:window];
        
        cameraBtn.enabled = !cameraBtn.enabled;
    }
}

#pragma mark - LXActionSheetDelegate代理
- (void)didClickOnButtonIndex:(NSInteger *)buttonIndex
{
    //KDLog(@"%d",(int)buttonIndex);
    int btnIndex = (int)buttonIndex;
    reportTableView.frame = CGRectMake(0, 4, screenW, screenH - 64);
    ipc = [[UIImagePickerController alloc] init];
    // 设置代理
    ipc.delegate = self;

    if(btnIndex == 0)
    {
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])  return;
        ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
        ipc.allowsEditing = YES;
        ipc.mediaTypes = [NSArray arrayWithObjects: @"public.image", nil];
        [self presentViewController:ipc animated:YES completion:nil];
    }
    else if(btnIndex == 1)
    {
        ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc] initImagePicker];
        elcPicker.maximumImagesCount = 4; //Set the maximum number of images to select to 100
        elcPicker.returnsOriginalImage = YES; //Only return the fullScreenImage, not the fullResolutionImage
        elcPicker.returnsImage = YES; //Return UIimage if YES. If NO, only return asset location information
        elcPicker.onOrder = YES; //For multiple image selection, display and return order of selected images
        elcPicker.mediaTypes = @[(NSString *)kUTTypeImage, (NSString *)kUTTypeMovie]; //Supports image and movie types
        elcPicker.imagePickerDelegate = self;
        [self presentViewController:elcPicker animated:YES completion:nil];
    }
    else if(btnIndex == 2)
    {
        cameraBtn.enabled = YES;
    }
}

#pragma mark - UIImagePickerControllerDelegate 在选择完图片后调用
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //销毁控制器
    [picker dismissViewControllerAnimated:YES completion:nil];
    //photoview出现
    //隐藏navigationbar
    self.navigationController.navigationBar.hidden = NO;
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    //获得图片
    UIImage *image = info[UIImagePickerControllerEditedImage];
    if(image == nil)
    {
        image = info[UIImagePickerControllerOriginalImage];
    }
    //保存图片
    [imgListP addObject:image];
    [imgCopy addObject:image];
    
    //选择图片成功后跳转界面
    GBReportViewController *collect = [[GBReportViewController alloc] init];
    
    for(int i = 0; i < imgListP.count; i++)
    {
        [collect.photoArrayS addObject:imgListP[i]];
    }
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    self.navigationController.navigationBar.hidden = NO;
    [self.navigationItem setBackBarButtonItem:backItem];
    [self.navigationController pushViewController:collect animated:YES];
    //KDLog(@"%lu",(unsigned long)imgCopy.count);
    //[photosCollectionView reloadData];
}

#pragma mark - imagePicker拍照取消操作
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    reportTableView.frame = CGRectMake(0, 4, screenW, screenH - 64);
    photoCount = 0;
    photoColumn = 0;
    [imgCopy removeAllObjects];
    [imgListP removeAllObjects];
    // 销毁控制器
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)displayPickerForGroup:(ALAssetsGroup *)group
{
    ELCAssetTablePicker *tablePicker = [[ELCAssetTablePicker alloc] initWithStyle:UITableViewStylePlain];
    tablePicker.singleSelection = YES;
    tablePicker.immediateReturn = YES;
    
    ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc] initWithRootViewController:tablePicker];
    elcPicker.maximumImagesCount = 1;
    elcPicker.imagePickerDelegate = self;
    elcPicker.returnsOriginalImage = YES; //Only return the fullScreenImage, not the fullResolutionImage
    elcPicker.returnsImage = YES; //Return UIimage if YES. If NO, only return asset location information
    elcPicker.onOrder = NO; //For single image selection, do not display and return order of selected images
    tablePicker.parent = elcPicker;
    // Move me
    tablePicker.assetGroup = group;
    [tablePicker.assetGroup setAssetsFilter:[ALAssetsFilter allAssets]];
    [self presentViewController:elcPicker animated:YES completion:nil];
}

#pragma mark ELCImagePickerControllerDelegate Methods
- (void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info
{
    [self dismissViewControllerAnimated:YES completion:nil];
    
    //隐藏navigationbar
    self.navigationController.navigationBar.hidden = YES;
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    
    NSMutableArray *images = [NSMutableArray arrayWithCapacity:[info count]];
    for (NSDictionary *dict in info)
    {
        if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypePhoto)
        {
            if ([dict objectForKey:UIImagePickerControllerOriginalImage])
            {
                UIImage* image=[dict objectForKey:UIImagePickerControllerOriginalImage];
                [images addObject:image];
                [imgListP addObject:image];
                [imgCopy addObject:image];
                //KDLog(@"代理imgcopy = %@",imgCopy);
                //[photosCollectionView reloadData];
            }
            else
            {
                KDLog(@"UIImagePickerControllerReferenceURL = %@", dict);
            }
        }
        else if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypeVideo)
        {
            if ([dict objectForKey:UIImagePickerControllerOriginalImage])
            {
                UIImage* image=[dict objectForKey:UIImagePickerControllerOriginalImage];
                [images addObject:image];
                [imgListP addObject:image];
                [imgCopy addObject:image];
                //[photosCollectionView reloadData];
            }
            else
            {
                KDLog(@"UIImagePickerControllerReferenceURL = %@", dict);
            }
        }
        else
        {
            KDLog(@"Uknown asset type");
        }
    }
    
    //选择图片成功后跳转界面
    GBReportViewController *collect = [[GBReportViewController alloc] init];
    
    for(int i = 0; i < imgListP.count; i++)
    {
        [collect.photoArrayS addObject:imgListP[i]];
    }
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    self.navigationController.navigationBar.hidden = NO;
    [self.navigationItem setBackBarButtonItem:backItem];
    [self.navigationController pushViewController:collect animated:YES];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    reportTableView.frame = CGRectMake(0, 4, screenW, screenH - 64);
}

#pragma mark - 从照片库选择图片的取消操作
- (void)elcImagePickerControllerDidCancel:(ELCImagePickerController *)picker
{
    reportTableView.frame = CGRectMake(0, 4, screenW, screenH - 64);
    [imgCopy removeAllObjects];
    [imgListP removeAllObjects];
    [self dismissViewControllerAnimated:YES completion:nil];
}
@end
